package com.qigao.mall.channel.weichat;

import com.alibaba.fastjson.JSONObject;
import com.qigao.mall.channel.ChannelCore;
import com.qigao.mall.channel.config.ChannelConstant;
import com.qigao.mall.channel.dto.ChannelQueryRespDto;
import com.qigao.mall.commons.dto.MerChannelDto;
import com.qigao.mall.commons.enums.*;
import com.qigao.mall.commons.param.ChannelReqParam;
import com.qigao.mall.commons.param.ChannelRespParam;
import com.qigao.mall.commons.utils.PayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 文档链接：https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=9_20&index=1
 */
@Service
public class WeichatPayQuery extends AbstractWeichatTrade implements ChannelCore {

    @Resource
    ChannelConstant channelConstant;

    private static final Logger logger= LoggerFactory.getLogger(WeichatPayQuery.class);

    @Override
    public boolean isSupport(PayProductEnum payProductEnum, ChannelActionEnum channelActionEnum, ChannelInfoEnum channelInfoEnum) {
        return ChannelActionEnum.ORDER_QEURY.equals(channelActionEnum) && channelInfoEnum.equals(ChannelInfoEnum.WEICHAT);
    }

    @Override
    protected String getSelfReqUrl() {
        return channelConstant.getWeichatOrderQueryUrl();
    }

    @Override
    public Map buildSelfReqParam(MerChannelDto merChannelDto, ChannelReqParam channelReqParam) {
        Map reqParam=new ConcurrentHashMap<String,String>();
        reqParam.put("appid", merChannelDto.getAppId());
        reqParam.put("mch_id", merChannelDto.getChannelPartenerNo());
        reqParam.put("nonce_str", PayUtil.getRandomString(16));
        // reqParam.put("transaction_id", merChannelDto.getThirdSeqNo());
        reqParam.put("out_trade_no", merChannelDto.getInnerSeqNo());
        return reqParam;
    }

    @Override
    protected ChannelRespParam buildSelfRespData(Map respMap, MerChannelDto merChannelDto) {
        ChannelQueryRespDto channelQueryRespDto =new ChannelQueryRespDto();
        channelQueryRespDto.setThirdTradeNo((String) respMap.get("transaction_id"));
        channelQueryRespDto.setInnerSeqNo(merChannelDto.getInnerSeqNo());
        channelQueryRespDto.setTimeEnd((String) respMap.get("time_end"));
        /**
         * SUCCESS—支付成功
         *
         * REFUND—转入退款
         *
         * NOTPAY—未支付
         *
         * CLOSED—已关闭
         *
         * REVOKED—已撤销（刷卡支付）
         *
         * USERPAYING--用户支付中
         *
         * PAYERROR--支付失败(其他原因，如银行返回失败)
         */
        String tradeStatus=(String)respMap.get("trade_state");
        if("USERPAYING".equals(tradeStatus)||"NOTPAY".equals(tradeStatus)){
            channelQueryRespDto.setTradeStatus(PayStatusEnum.PAY_INIT);
        }else if("CLOSED".equals(tradeStatus)||"REVOKED".equals(tradeStatus)||"PAYERROR".equals(tradeStatus)){
            channelQueryRespDto.setTradeStatus(PayStatusEnum.PAY_CLOSE);
        }else if("SUCCESS".equals(tradeStatus)||"REFUND".equals(tradeStatus)){
            channelQueryRespDto.setTradeStatus(PayStatusEnum.PAY_SUCCESS);
        }else if("TRADE_FINISHED".equals(tradeStatus)){
            channelQueryRespDto.setTradeStatus(PayStatusEnum.PAY_FINISH);
        }
        String totalFee=(String) respMap.get("total_fee");
        BigDecimal tradeAmt= new BigDecimal(totalFee).divide(new BigDecimal(100));
        channelQueryRespDto.setTradeAmt(tradeAmt);
        channelQueryRespDto.setRetCode(tradeStatus);
        channelQueryRespDto.setRetMsg((String)respMap.get("trade_state_desc"));
        channelQueryRespDto.setBuylerId((String)respMap.get("openid"));
        String retStr= JSONObject.toJSONString(channelQueryRespDto);
        ChannelRespParam channelRespParam=new ChannelRespParam();
        channelRespParam.setRespCode(ChannelCodeEnum.SUCCESS.getCode());
        channelRespParam.setRespMsg(ChannelCodeEnum.SUCCESS.getName());
        channelRespParam.setRespContent(retStr);
        return  channelRespParam;
    }


}
